using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PokerStar.Core
{
    public class DeckOfCards
    {
        private const int Size = 52;

        private readonly Card[] _cards = InitDeck();
        private IList<int> _sequence = InitSequence();
        private int _next;

        public DeckOfCards()
        {
            Reset();
        }

        private static IList<int> InitSequence()
        {
            return Enumerable.Range(0, Size).ToList();
        }

        private static Card[] InitDeck()
        {
            var numbers = new[] { '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A' };
            IList<Card> cards = new List<Card>(Size);
            foreach (Suit suit in Enum.GetValues(typeof(Suit)))
            {
                foreach (var number in numbers)
                {
                    cards.Add(new Card(suit, number));
                }
            }
            return cards.ToArray();
        }

        public void Reset()
        {
            _next = 0;

            var r = new Random();
            var times = 200;
            while (times-- > 0)
            {
                var a = r.Next(Size);
                var b = r.Next(Size);
                var t = _sequence[a];
                _sequence[a] = _sequence[b];
                _sequence[b] = t;
            }
        }

        public override string ToString()
        {
            var buffer = new StringBuilder();
            for (int i = 0; i < 13; i++)
            {
                for (int j = 0; j < 4; j++)
                {
                    var s = _sequence[i * 4 + j];
                    buffer.Append(_cards[s]);
                    buffer.Append(' ');
                }
                buffer.AppendLine();
            }
            return buffer.ToString();
        }

        public Card Next()
        {
            return _cards[_sequence[_next++]];
        }
    }
}